<template>
	<view>
		<st-mc-framework :navTitle="ModuleTitle" @changeLevel="changeLevel" ref="framework"
			@AddModuleData_select='AddModuleData_select'>

			<template #content>
				<view class="content" style="width: 100%;height: 100%;">
					<view class="contentBox" style="flex: 1;">
						<view class="container">

							<u--form class="u_form" labelPosition="left" :model="baseFormData" ref="uForm">

								<u-row justify="space-between" gutter="20">
									<u-col span="12">
										<u-cell icon="calendar" size="large">
											<view slot="title" class="u-slot-title">
												<text class="u-cell-text u-cell_text">申请人填写</text>
											</view>
										</u-cell>
									</u-col>
								</u-row>
								<u-row justify="space-between" gutter="20">
									<u-col span="4">

										<u-form-item labelWidth="auto" label="设备:">
											<u--input v-model="baseFormData.EquipmentName" placeholder="设备" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="申请人:">
											<u--input v-model="baseFormData.ApplyForMan" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="申请时间:">
											<u--input v-model="baseFormData.ApplyForTime" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>

								<u-row justify="space-between" gutter="20">
									<u-col span="8">
										<u-form-item labelWidth="auto" label="故障描述:" required>
											<u--input v-model="baseFormData.BXContent" placeholder="请输入故障描述"
												:readonly="disableShow == 2||disableShow == 3" border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>

								<u-row justify="space-between" gutter="20">
									<u-col span="12">
										<u-cell icon="calendar" size="large">
											<view slot="title" class="u-slot-title">
												<text class="u-cell-text u-cell_text">维修人填写</text>
											</view>
										</u-cell>
									</u-col>
								</u-row>

								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="维修编号:">
											<u--input v-model="baseFormData.BillNO" placeholder="自动带出维修编号" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="维修人:" required
											@click="openBaseScreen('人员')" required>
											<u--input v-model="baseFormData.MaintainMan" placeholder="请选择维修人" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="维修内容:" required>
											<u--input v-model="baseFormData.GZCause" placeholder="请输入维修内容"
												:readonly="disableShow == 1||disableShow == 3" border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>
								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="维修方式:" required @click="addWay('WXFS')">
											<u--input v-model="baseFormData.WayName" placeholder="请选择维修方式" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="维修费用:">
											<u--input v-model="baseFormData.Cost" placeholder="请输入维修费用" type="number"
												:readonly="disableShow == 1||disableShow == 3" border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="维修状态:">
											<u--input v-model="baseFormData.WCStatusName" placeholder="维修状态" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>
								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="维修结果:" required @click="addWay('SBWX')">
											<u--input v-model="baseFormData.FResultName" placeholder="请选择维修结果" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="维修开始时间:">
											<u--input v-model="baseFormData.BeginTime" placeholder="自动带出开始时间" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="维修结束时间:">
											<u--input v-model="baseFormData.WCTime" placeholder="自动带出结束时间" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>
							</u--form>




							<view class="AddBottomBox">
								<button class="CancelBtn" @click="addplus()">新增配件</button>
							</view>
							<view class="table" style="text-align: center;margin: auto;">
								<table>
									<tr>
										<th width='15%'>操作</th>
										<th>配件名称</th>
										<th>数量</th>
									</tr>
									<tr v-for="(item, index) in tableData" :key="index">
										<td>
											<uni-icons type="trash" size="30" @click="trash(index)"></uni-icons>
										</td>
										<td @click="addproducplname(item,index)">
											<u--textarea v-model="item.ProductPJName" autoHeight border="none"
												placeholder="请选择配件" disabled class="fixed-textarea"></u--textarea>
										</td>
										<td>
											<u--input placeholder="请输入数量" type="number" v-model="item.Num"
												inputAlign='center' style="border-bottom: 0px !important;"
												:readonly="!buttonShow" border="none"></u--input>
										</td>
									</tr>
								</table>
							</view>
						</view>


					</view>
					<view class="DetailsbottomBtns" v-show="buttonShow">
						<button @click="submit" class="button1">
							{{buttonTitle}}
						</button>
					</view>
				</view>
			</template>
		</st-mc-framework>
		<u-action-sheet :actions="StateList" :show="StateShow" @select="StateClick"
			@close="StateShow=false"></u-action-sheet>

		<u-toast ref="uToast"></u-toast>
		<u-modal :show="modalshow" :title="modaltitle" width="400" @confirm='modalconfirm'>
			<view class="slot-content">
				{{modalcontent}}
			</view>
		</u-modal>
		<m-loading :text="loadingName" v-model="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>


	</view>
</template>

<script>
	import {
		getTimeStamp,
		getFormatDate,
		getFormatDateTime,
		getBefore7DateTime,
		formatDateTime,
		navigateMixin,
		baseAddModuleData_select,
		getchangeLevel
	} from '@/st_mes_zs/common/base.js';
	export default {
		mixins: [navigateMixin, baseAddModuleData_select],
		data() {
			return {
				baseFormData: {
					FaultDocID: 0,
					QRMan: '',
					WCMan: '',
					EquipmentName: '',
					ApplyForMan: '',
					ApplyForTime: '',
					BXContent: '',
					BillNO: '',
					MaintainMan: '',
					QREmplID: 0,
					WXQREmplID: 0,
					GZCause: '',
					Way: '',
					WayName: '',
					Cost: '',
					WCStatus: '',
					FResult: 0,
					FResultName: '',
					BeginTime: '',
					WCTime: '',
					BillDate: '',
					XTID: null,

				},
				sexs: [{
					text: '合格',
					value: 0
				}, {
					text: '不合格',
					value: 1
				}],
				buttonShow: true,
				buttonTitle: '保存',
				disableShow: 1,


				StateShow: false,
				StateList: [],
				producplnameIndex: 0,
				tableData: [],
				modalcontent: '',
				WXQRManNum: null, //确认人值


				modalshow: false,
				modaltitle: '提示',
				modalcontent: '',
				FWorkshopID: null, //模块id
				ModuleTitle: '', //标题
				showMLoading: false,
				loadingName: '正在加载中……',
			};
		},
		onReady() {
			var that = this
			uni.hideLoading();
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			that.FWorkshopID = MesBasicInfo.FWorkshopID;
			that.ModuleTitle = appConfigInfo.ActiveModule.ModuleName
			this.ChangedisableShow()
		},
		onLoad(onLoad) {
			var that = this
			that.$safeStatus({
				payload: '其他', // 要传递的数据
			});
			// 缓存状态引用
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = this.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			// 统一处理加载状态
			const setLoading = (state) => this.showMLoading = state;
			// 主处理逻辑
			if (onLoad.MaintainEquipmentID) {
				setLoading(true);
				that.queryList('列表', onLoad.MaintainEquipmentID)
				return;
			}
			if (onLoad.Detailsitem) {
				setLoading(true);
				const dispatchItem = JSON.parse(onLoad.Detailsitem);
				if (dispatchItem.MaintainEquipmentID) {
					setLoading(true);
					that.queryList('列表', dispatchItem.MaintainEquipmentID)
					return;
				}
				const formDefaults = {
					...dispatchItem,
					MoludName: dispatchItem.MoludName ? dispatchItem.MoludName : dispatchItem.MoludCode,
					BXContent: dispatchItem.GZContent
				}
				console.log(formDefaults);
				this.baseFormData = Object.assign(this.baseFormData, formDefaults);
			}

			// 统一处理表单默认值
			const formDefaults = {
				ApplyForMan: UserInfo.EmplName,
				CheckupID: UserInfo.EmplID,
				ApplyForTime: getFormatDateTime(new Date()),
				BillDate: getFormatDateTime(new Date()),
				EquipmentID: that.baseFormData.EquipmentID ? that.baseFormData.EquipmentID : MesBasicInfo.warehouse
					.EquipmentID,
				EquipmentName: that.baseFormData.EquipmentName ? that.baseFormData.EquipmentName : MesBasicInfo
					.warehouse.EquipmentName,
			};
			this.assignFormData(this.baseFormData, formDefaults);
			setLoading(false);
		},
		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},

		onShow() {
			var that = this
			uni.$on('refreshDetail', (res) => {
				console.log(res.data);
				this.getValue(res.data); // 调用目标方法
			});
		},

		onUnload() {
			var that = this;
			uni.$off('refreshDetail');
			uni.$off('reportingDetail_Choice')
		},
		mounted() {
			var that = this;
			uni.$on('reportingDetail_Choice', function(ret) {
				var formDefaults = {}
				if (ret.type == '配件') {
					formDefaults = {
						ProductPJID: ret.data.ProductPJID,
						MoludName: ret.data.ProductPJName,
					}
					that.assignFormData(that.tableData[that.producplnameIndex], formDefaults);
				}
			})

		},
		methods: {

			// 创建表单赋值工具函数
			assignFormData(target, defaults = {}) {
				var that = this;
				Object.keys(defaults).forEach(key => {
					target[key] = defaults[key];
				});
				that.$forceUpdate();
			},
			replaceFormData(target, source, defaults = {}) {
				Object.keys(defaults).forEach(key => {
					target[key] = source[key] || defaults[key];
				});
				this.$forceUpdate()
			},
			async AddModuleData_select(res) {
				try {
					const backDelta = await this.GetModuleData_select(res);
				} catch (error) {
					console.error('返回操作失败:');
				}
			},
			modalconfirm() {
				var that = this
				that.modalshow = false
			},
			showModal(title, content) {
				this.modaltitle = title;
				this.modalcontent = content;
				this.modalshow = true;
			},

			trash(index) {
				var that = this
				if (that.buttonShow) {
					that.tableData.splice(index, 1)
					this.$forceUpdate()

				}
			},
			addplus() {
				var that = this
				if (that.buttonShow && that.disableShow == 2) {
					var obj = {
						Num: 1,
						ProductPJName: '',
						ProductPJID: null,
						MaintainEquipmentDeID: 0
					}
					that.tableData.push(obj)
					this.$forceUpdate()
				}
			},
			addproducplname(item, index) {
				var that = this;
				if (that.buttonShow) {

					that.producplnameIndex = index
					that.openBaseScreen('配件')
				}
			},


			openBaseScreen1(str, type, num) {
				var that = this;
				var obj
				var url
				uni.hideKeyboard(); //隐藏软键盘
				if (that.buttonShow) {
					switch (type) {
						case 'radio': // 单选项
							url = '/commonPage/Tool/baseScreen';
							if (str == '配件') {

								obj = {
									allowClear: false,
									cmd: 'getsProductPJ',
									type: str,
									ListeningName: 'reportingDetail_Choice',
									// multiple: false,
									serverSearch: {
										isPaging: true, //是否分页
										searchKey: 'ProductPJName', //搜索关键词，应包含在param中
										showText: 'ProductPJName', //查询结果显示的字段
										pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中
										ChoiceDataKey: 'ProductPJID',
										ChoiceDataData: that.tableData[that.producplnameIndex].ProductPJID, //选中的数据
									},
									param: {
										ProductPJName: '',
										SearchKey: '',
										PageIndex: 1,
										PageSize: 30,
									}
								}

							}
							break;

						default:
							break;
					}

					if (!this.$utils.isEmpty(obj)) {

						// console.log(url);
						// console.log(obj);
						this.$store.commit('ChangeAndSetStateData', {
							Name1: 'BaseScreenParm',
							data: obj
						})

						uni.navigateTo({
							url: url
						})
					}


				}
			},
			ChangedisableShow() {
				var that = this
				if (that.buttonTitle == '保存') {
					that.disableShow = 1
				} else {
					that.disableShow = 2
				}
			},

			addPeriodTypeClick() {
				var that = this
				that.disableShow = 2
				console.log('cccccccccccc');
				if (!that.baseFormData.BeginTime) {
					that.buttonTitle = '开始维修'
				} else if (that.baseFormData.BeginTime) {
					that.buttonTitle = '结束维修'
				}
				if (that.baseFormData.MaintainEquipmentID && that.baseFormData.BeginTime && that.baseFormData
					.WCTime) {
					that.buttonShow = false
					that.disableShow = 3
				}
				that.$forceUpdate()
			},
			StateClick(e) {
				var that = this;
				console.log(e);
				console.log(that.StateName);
				var formDefaults = {}
				if (that.StateName == 'SBWX') {
					console.log(e.id);
					formDefaults = {
						FResult: e.id,
						FResultName: e.name
					}
				} else {
					formDefaults = {
						Way: e.id,
						WayName: e.name
					}
				}
				that.assignFormData(that.baseFormData, formDefaults);

			},
			addWay(str) {
				var that = this;
				if (that.disableShow == 2 && that.buttonShow == true) {
					that.StateName = str
					console.log(str);
					that.Request.request('getViewState', {
						FType: str
					}, function(ret) {
						console.log(ret.data.ds);
						if (ret.status == 200) {
							that.StateList = ret.data.ds
						}
					})
					this.StateShow = true
				}

			},
			getValue(payload) {
				var that = this;
				const {
					type,
					...data
				} = payload;
				if (payload === '返回') return;
				const typeHandlers = {
					'人员': () => ({
						MaintainMan: data.UserName,
					}),
					'模具': () => ({
						MoludID: data.MoludID,
						MoludName: data.MoludCode
					}),
					'配件': () => ({
						ProductPJID: data.ProductPJID,
						ProductPJName: data.ProductPJName
					}),
				};
				console.log(typeHandlers);
				if (typeHandlers[type]) {
					console.log(typeHandlers[type]());
					if (type == '配件') {
						console.log(typeHandlers[type]());
						console.log(that.tableData[that.producplnameIndex]);
						Object.assign(that.tableData[that.producplnameIndex], typeHandlers[type]());
					} else {
						Object.assign(that.baseFormData, typeHandlers[type]());
					}
				}
			},

			openBaseScreen(str, val) {
				var that = this;
				var obj;
				var show = false


				if (str == '人员') {
					if (that.disableShow == 2 && that.buttonShow == true) {
						show = true
					}
					obj = {
						cmd: 'getEmplByJobName',
						type: str,
						serverSearch: {
							isPaging: true, //是否分页
							pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
							searchShow: false, //是否查询
							searchKey: 'searchKey', //搜索关键词，应包含在param中
							showText: 'UserName', //查询结果显示的字段
						},
						param: {
							JobName: '',
							PageIndex: 1,
							PageSize: 30
						}
					}
				} else if (str == '配件') {
					show = true
					obj = {
						cmd: 'getsProductPJ',
						type: str,
						serverSearch: {
							isPaging: true, //是否分页
							searchShow: true, //是否查询
							pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中							
							searchKey: 'ProductPJName', //搜索关键词，应包含在param中
							showText: 'ProductPJName', //查询结果显示的字段
						},
						param: {
							ProductPJName: '',
							PageIndex: 1,
							PageSize: 30,
						}
					}

				}

				if (show == true) {
					uni.navigateTo({
						url: `../common/baseScreen?obj=${JSON.stringify(obj)}`,
						animationType: 'slide-in-right',
						animationDuration: 300
					});
				}


			},



			submit() {
				var that = this
				var msg
				var show = true

				if (that.baseFormData.BXContent == '' || that.baseFormData.BXContent == null) {
					msg = '请输入故障描述'
					show = false
				}

				if (that.buttonTitle == '开始维修') {
					if (that.baseFormData.MaintainMan == '' || that.baseFormData.MaintainMan == null) {
						msg = '请选择人员'
						show = false
					} else if (that.baseFormData.GZCause == '' || that.baseFormData.GZCause == null) {
						msg = '请输入维修内容'
						show = false
					} else if (that.baseFormData.WayName == '' || that.baseFormData.WayName == null) {
						msg = '请选择维修方式'
						show = false
					}
				} else if (that.buttonTitle == '结束维修') {
					if (that.baseFormData.FResultName == '' || that.baseFormData.FResultName == null) {
						msg = '请选择维修结果'
						show = false
					}
				}

				if (show) {
					if (that.buttonTitle == '开始维修') {
						const formDefaults = {
							Cost: that.baseFormData.Cost ? that.baseFormData.Cost : 0,
						}
						that.assignFormData(that.baseFormData, formDefaults)
					}
					var obj = {
						MaintainEquipmentID: that.baseFormData.MaintainEquipmentID ? that.baseFormData
							.MaintainEquipmentID : 0,
						ApplyForMan: that.baseFormData.ApplyForMan,
						EquipmentID: that.baseFormData.EquipmentID,
						ApplyForTime: that.baseFormData.ApplyForTime,
						BXContent: that.baseFormData.BXContent,
						BillNO: that.baseFormData.BillNO,
						MaintainMan: that.baseFormData.MaintainMan,
						GZCause: that.baseFormData.GZCause,
						Way: that.baseFormData.Way,
						Cost: that.baseFormData.Cost != null ? that.baseFormData.Cost : '',
						WCStatus: that.baseFormData.WCStatus,
						FResult: that.baseFormData.FResult ? that.baseFormData.FResult : 0,
						BeginTime: that.baseFormData.BeginTime,
						WCTime: that.baseFormData.WCTime,
						BillDate: that.baseFormData.BillDate,
						FType: 'SBWX',
						XTID: that.baseFormData.XTID,
						FWorkshopID: that.FWorkshopID,
						Num: that.tableData.map(item => item.Num).join(','),
						ProductPJID: that.tableData.map(item => item.ProductPJID).join(','),
						MaintainEquipmentDeID: that.tableData.map(item => item.MaintainEquipmentDeID).join(','),
						ProductPJName: that.tableData.map(item => item.ProductPJName).join(','),
						QRMan: that.baseFormData.QRMan,
						WCMan: that.baseFormData.WCMan,
						QREmplID: that.baseFormData.QREmplID,
						WXQREmplID: that.baseFormData.WXQREmplID,
						FaultDocID: that.baseFormData.FaultDocID,
					}
					console.log(obj);
					that.Request.request('saveMaintainEquipment', obj, function(ret) {
						console.log(ret);
						if (ret.status == 200) {
							that.$refs.uToast.show({
								title: '保存',
								type: 'success',
								message: '保存成功'
							})
							that.queryList('刷新', ret.data.ds[0].MaintainEquipmentID)

						}
					})
				} else {

					that.showModal('报错', msg);
				}
			},
			queryList(str, id) {
				var that = this
				try {
					that.Request.request('getMaintainEquipmentDetail', {
						MaintainEquipmentID: id
					}, (ret) => {
						console.log(ret.data);
						that.showMLoading = false
						const [firstItem] = ret.data.ds;
						const formDefaults = {
							...firstItem,
							ApplyForTime: firstItem.ApplyForTime ? firstItem.ApplyForTime.split('T')[0] : '',
							WCTime: formatDateTime(firstItem.WCTime),
							BeginTime: formatDateTime(firstItem.BeginTime),
						};
						if (str == '列表') {
							formDefaults.MaintainMan = that.baseFormData.MaintainMan ? that.baseFormData
								.MaintainMan : that.$store.state.UserInfo.EmplName
						}
						console.log(firstItem);
						that.tableData = ret.data.ds1
						that.assignFormData(that.baseFormData, formDefaults)
						that.addPeriodTypeClick()

					}, (err) => {
						that.showMLoading = false
					})
				} catch (e) {
					console.log(e)
					that.showMLoading = false
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},


			changeLevel(list, data, row) {
				getchangeLevel(data)
				uni.$emit('refreshList');
			},
		}
	}
</script>

<style lang="scss">
	@import "../css/index.css";

	.u_form {
		.u-cell__body {
			padding: 5px 0 !important;

			.u-cell_text {
				font-weight: 600 !important;
			}
		}
	}



	// 查询按钮
	.AddBottomBox {
		width: 100%;
		display: flex;
		align-items: center;
		padding: 2px 5px;
		justify-content: flex-end;
		box-sizing: border-box;

		.CancelBtnIcon {
			.icon {
				padding: 0;
				margin: 0;
			}
		}

		.CancelBtn {
			margin: 0 5px;
			align-items: center;
			text-align: center;
			display: flex;
			justify-content: center;
			background-color: #fff;
			color: #51d0d0;
			border: 1px solid #51d0d0;
			min-height: 45px;
			min-width: 80px;

			border-radius: 4px;
			font-size: 14px;
			box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
			transition: all 0.3s ease;

			&:active {
				background-color: #e6f7f7;
				transform: translateY(1px);
			}
		}
	}
</style>